const axios = require("axios");

// 环境变量及配置
const BASE_URL = "https://ai.totemlife.cn";
const DEFAULT_WORKSPACE_LINK = "528b8c1d-3854-499e-b754-5ae9776177bd";
const DEFAULT_WORKSPACE_ID = 1;

// 通用请求方法
const request = async (method, url, data = {}) => {
    const headers = {
        Accept: "application/json",
        Authorization: `Bearer ${process.env.CC_KEY}`,
    };
    try {
        const options = { method, url, headers };
        if (method === "POST" || method === "PATCH") options.data = data;
        const response = await axios(options);
        return response.data;
    } catch (error) {
        console.error(`❌ 请求失败: ${url}`, error.message);
        throw error;
    }
};

// 测试 API 连接
const auth = async () => {
    const url = `${BASE_URL}/api/v1/auth`;
    const data = await request("GET", url);
    console.log("✅ API 连接成功:", data);
};

// 获取工作区列表
const getWorkspaces = async () => {
    const url = `${BASE_URL}/api/v1/workspaces`;
    const data = await request("GET", url);
    console.log("📚 工作区列表:", data);
};

// 上传链接到工作区
const uploadLink = async (link) => {
    const uploadURL = `${BASE_URL}/api/v1/document/upload-link`;
    try {
        await request("POST", uploadURL, { link });
        console.log(`✅ 上传链接成功: ${link}`);
    } catch {
        console.error(`❌ 上传链接失败: ${link}`);
    }
};

// 查询工作区中的文档
const listDocuments = async () => {
    const url = `${BASE_URL}/api/v1/documents`;
    const data = await request("GET", url);
    console.log("📄 文档列表:", JSON.stringify(data));
};

// 发送 LLM 问答请求
const query = async (message) => {
    const url = `${BASE_URL}/api/v1/workspace/${DEFAULT_WORKSPACE_LINK}/chat`;
    const payload = {
        message,
        mode: "query",
        sessionId: "test-session-1",
        attachments: [],
    };
    const data = await request("POST", url, payload);
    console.log("💬 LLM 回复:", data);
};

// LLM 主测试流程
const test = async () => {
    console.log("🚀 开始测试 API 功能");
    //await auth();
    //await getWorkspaces();
    //await listDocuments();
    //await uploadLink('https://www.frontiersin.org/journals/nutrition/articles/10.3389/fnut.2024.1447059/full');
    await query("图腾生命医学是一家什么样的公司？");
};

const cc = {
    BASE_URL,
    DEFAULT_WORKSPACE_LINK,
    DEFAULT_WORKSPACE_ID,
    request,
    getWorkspaces,
    uploadLink,
    listDocuments,
    query,
    test,
};
module.exports = cc;
